import os

from flask import Blueprint, request, jsonify, render_template, redirect, current_app, session
from werkzeug.security import generate_password_hash
from werkzeug.utils import secure_filename

from applications.models.frontend import *  # 确保导入前台用户模型
from functools import wraps

# 创建sys
bp = Blueprint('users', __name__)


@bp.route('/userInfo')
def userInfo():
    user_id = session.get('user_id')
    articleCates = ArticleCate.query.all() #获取文章分类
    articles = Article.query.filter_by(user_id=user_id).all()  # 获取用户的文章

    if not user_id:
        return redirect('/login')  # 用户未登录，重定向到登录页面
    userinfo = User.query.filter_by(id=user_id).first()
    if not userinfo:
        return jsonify({"error": "User not found"}), 404  # 用户未找到，返回404错误
    # 计算年龄
    today = datetime.today()
    if userinfo.birthday:
        age = today.year - userinfo.birthday.year - (
            (today.month, today.day) < (userinfo.birthday.month, userinfo.birthday.day)
        )
    else:
        age = "未知"  # 如果生日信息缺失，设置为"未知"

    # 创建用户信息字典
    user = {
        'username': userinfo.username,
        'password': '',
        'age': age,
        'phone': userinfo.phone,
        'birthday': userinfo.birthday.strftime("%Y-%m-%d") if userinfo.birthday else '',  # 格式化生日
        'address': userinfo.address if userinfo.address else '',
        'sex': userinfo.sex,
        'avatar': userinfo.avatar,
        'description': userinfo.description if userinfo.description else '',
    }

    print(user)  # 可选，调试用

    return render_template('user/login/userInfo.html', user=user, articleCate=articleCates, articles=articles)


# 修改用户
@bp.route('/user/update', methods=['POST'])
def updateUser():
    username = request.form.get('username')
    password = request.form.get('password')
    sex = request.form.get('sex')
    phone = request.form.get('phone')
    description = request.form.get('description')
    birthday = request.form.get('birthday')
    address = request.form.get('address')

    avatar = request.files.get('file')
    user_id = session.get('user_id')

    # 根据 user_id 查找用户
    user = User.query.get(user_id)
    if user:
        # 更新用户信息
        user.username = username
        user.password = password
        user.description = description
        user.birthday = birthday
        user.address = address
        user.phone = phone
        user.sex = sex
        # 如果用户设置了新密码
        if password:
            user.password = generate_password_hash(password)
        # 如果用户上传了新头像
        if avatar:
            filename = secure_filename(avatar.filename)
            # 使用 os.path.join 确保路径在不同操作系统上兼容
            file_path = os.path.join('applications',current_app.config['UPLOADED_PHOTOS_DEST'], filename)
            avatar.save(file_path)
            print('avatar:', file_path)
            user.avatar = '/static/upload/'+filename  # 存储文件名

        # 将更改保存到数据库
        db.session.commit()

        response = jsonify({"message": "更新成功", "data": user.to_dict(), "code": 200})
    else:
        # 如果用户不存在
        response = jsonify({"message": "用户未找到,更新失败", "code": 400})
    return response

